<?php
// +----------------------------------------------------------------------
// | astp [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author 荒年 < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 素材上传
// +----------------------------------------------------------------------
namespace app\wewhat\controller;

use think\Controller;
use app\wewhat\service\HttpRequest;
use app\wewhat\service\Accesstoken;
use app\wewhat\model\Material as materialModel;
use think\Db;
use think\facade\Env;

class Material extends Controller
{
  // 素材列表
  public function lst()
  {
    $material = Db::name('material')->paginate(20);
    $this->assign('material',$material);
    return view();
  }

  //新增素材
  public function add()
  {
    if($this->request->isPost()) {
      $model = new materialModel();
      $post = $this->request->post();
      $path = Env::get('root_path') . 'public'.$post['media'];
      $media_id = $this->uploadMaterial($path);
      $post['media_id'] = $media_id;
      $result = $model->save($post);
      if( $result ){
        $this->success('添加素材成功','material/lst');
      } else {
        $this->error('添加素材失败');
      }
    } else {
     return $this->fetch();
    }
  }

  public function uploadMaterial($path,$type='image',$is_forever = 0)
  {
    $access = new Accesstoken();
    $http = new HttpRequest();
    if ($is_forever == 0) {
      // 临时素材
      $urls = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s';
    } else {
      // 永久素材
      $urls = 'https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=%s';
    }
    $url = sprintf($urls,$access->getAccessToken(),$type);
    //上传素材到微信公众平台
    $json = $http->http_request($url,[],$path);
    $arr = json_decode($json,true);
    return empty($arr['media_id']) ? '' : $arr['media_id'];
  }

}

?>